<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

  <head>

    <title>Simple Constructs: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
    <meta name="keywords" content="ruby constructs,ruby study notes,ruby guide,free ruby programming course,best ruby guide,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
    <meta name="Distribution" content="Global" />
    <meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
    <meta name="copyright" content="Satish Talim 2007 and beyond..." />
    <meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
    <meta name="robots" content="index,follow" />
    <meta http-equiv="Expires" content="0" />
    <meta name="revisit-after" content="1 days" />

    <link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
    <link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
    <link rel="icon" type="image/ico" href="/images/favicon.ico" />


    <!-- Google +1 button code -->
    <link rel="canonical" href="/satishtalim/simple_constructs.html" />
    <script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
    <!-- Google Analytics code -->
    <script type="text/javascript">

     var _gaq = _gaq || [];
     _gaq.push(['_setAccount', 'UA-59044-10']);
     _gaq.push(['_trackPageview']);

     (function() {
       var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
       ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
     })();

    </script>
    <!-- Google Analytics code ends -->
  </head>

  <body>
    <!-- wrap starts here -->
    <div id="wrap">

      <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

      </div>

      <div id="menu">
        <ul>
          <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
          <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
          <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
          <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
          <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
          <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
          <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Ruby Learning site">Blog</a></li>
          <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
          <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
          <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
      </div>

      <!-- content-wrap starts here -->
      <div id="content-wrap">

        <div id="main">

          <div id="main-inner"><a name="TemplateInfo"></a>
            <h1>Simple Constructs</h1>

            <p class="post-footer align-right">
              <strong>
                <a href="/satishtalim/more_on_strings.html">&lt;More on Strings | </a>
                <a href="/satishtalim/tutorial.html">TOC | </a>
                <a href="/satishtalim/ruby_blocks.html">Ruby Blocks&gt;</a>
              </strong>
            </p>

            <p>Let's explore some very simple constructs available in Ruby. The example below <strong>p014constructs.rb</strong>  illustrates the <strong>if else end</strong> construct. By the Ruby convention, <strong>if</strong> and <strong>while</strong> do not require parenthesis.</p>

            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p014constructs.rb
                # In Ruby, nil and false evaluate to false,
                # everything else (including true, 0) means true
                # nil is an actual object
                # if else end
                var = 5
                if var &gt; 4
                  puts "Variable is greater than 4"
                  puts "I can have multiple statements here"
                  if var == 5
                    puts "Nested if else possible"
                  else
                    puts "Too cool"
                  end
                else
                  puts "Variable is not greater than 5"
                  puts "I can have multiple statements here"
                end
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <p>An example of using <strong>elsif</strong> is there in the program <strong>p015elsifex.rb</strong> as shown below:</p>

            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p015elsifex.rb
                # elseif example

                # Original example
                puts "Hello, what's your name?"
                STDOUT.flush
                name = gets.chomp
                puts 'Hello, ' + name + '.'

                if name == 'Satish'
                  puts 'What a nice name!!'
                else
                  if name == 'Sunil'
                    puts 'Another nice name!'
                  end
                end

                # Modified example with elseif
                puts "Hello, what's your name?"
                STDOUT.flush
                name = gets.chomp
                puts 'Hello, ' + name + '.'

                if name == 'Satish'
                  puts 'What a nice name!!'
                elsif name == 'Sunil'
                  puts 'Another nice name!'
                end

                # Further modified
                puts "Hello, what's your name?"
                STDOUT.flush
                name = gets.chomp
                puts 'Hello, ' + name + '.'

                # || is the logical or operator
                if name == 'Satish' || name == 'Sunil'
                  puts 'What a nice name!!'
                end
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <p>Some common conditional operators are: ==, != &gt;=, &lt;=, &gt;, &lt;</p>

            <p><strong>unless</strong>, as a statement or a modifier, is the opposite of <strong>if</strong>: it executes code only if an associated expression evaluates to <strong>false</strong> or <strong>nil</strong>. Ruby's <strong>unless</strong> construct begins with <strong>unless</strong> and ends with <strong>end</strong>. The body is the text between the two.</p>

            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                unless ARGV.length == 2
                  puts "Usage: program.rb 23 45"
                  exit
                end
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <p>In the above program, the body is executed unless the number of elements in the array is equal to 2 (meaning that both arguments were given). The method <strong>Kernel.exit</strong> terminates your program, returning a status value to the operating system.</p>

            <p>Loops like the <strong>while</strong> loop are available. Again, the example below illustrates the same.</p>

            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # Loops
                var = 0
                while var &lt; 10
                  puts var
                  var += 1
                end
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <h3>Conditional ?:</h3>

            <p>As a concise alternative to simple if/else statements we can use the conditional or ternary <b>?:</b> operator. It is the only ternary operator (three operands) in Ruby. It has the following basic structure:</p>
            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                (condition) ? (result if condition is true) : (result if condition is false)
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <p>The first operand appears before the question mark. The second operand appears between the question mark and the colon. An the third operand appears after the colon. The question mark must appear on the same line as the first argument and the colon must appear on the same line as the second argument. The <strong>?:</strong> operator always evaluates its first operand. If the first operand is anything other than <strong>false</strong> or <strong>nil</strong>, the value of the expression is the value of the second operand. Otherwise, if the first operand is <strong>false</strong> or <strong>nil</strong>, then the value of the expression is the value of the third operand. The <strong>?:</strong> operator acts like a compact <strong>if/then/else</strong> statement. Let's look at an example:</p>

            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                age = 15
                # We talk about the Range class later on
                # will output teenager
                puts (13...19).include?(age) ? "teenager" : "not a teenager"
              </textarea>
              <!-- InstanceEndEditable -->
            </div>
            <p>The ternary operator also can be useful for conditional assignments:</p>
            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                age = 23
                person = (13...19).include?(age) ? "teenager" : "not a teenager"
                puts person # => "not a teenager"
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <h3>Statement modifiers</h3>

            <p>Ruby statement modifiers are a useful shortcut if the body of an <strong>if</strong> or <strong>unless</strong> statement is just a single expression. Simply write the expression, followed by <strong>if</strong> or <strong>unless</strong> and the condition. For example, here's a simple <strong>if</strong> statement.</p>

            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                puts "Enrollments will now Stop" if participants > 2500
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <h3>Case Expressions</h3>

            <p>This form is fairly close to a series of <strong>if</strong> statements: it lets you list a series of conditions and execute a statement corresponding to the first one that's true. For example, leap years must be divisible by 400, or divisible by 4 and not by 100. Also, remember that <strong>case</strong> returns the value of the last expression executed.</p>

            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                year = 2000
                leap = case
                       when year % 400 == 0 then true
                       when year % 100 == 0 then false
                       else year % 4   == 0
                       end
                puts leap
                # output is: true
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <h3>nil is an Object</h3>

            <p>In Ruby, <strong>nil</strong> is an actual object. You can call methods on <strong>nil</strong>, just like any other object. You can add methods to <strong>nil</strong>, just like any other object.<br /><br />In Ruby, <strong>nil</strong> and <strong>false</strong> evaluate to false, everything else (including <strong>true</strong>, 0) means true.</p>

            <h3>Difference between FALSE and NIL</h3>

            <p>Though we still have to talk about classes, nevertheless here is some additional information for you. <strong>nil</strong> and <strong>false</strong> are not the same things. Both have a false value and also remember that everything in Ruby is an object. See the following program:</p>

            <div class="column2">
              <!-- InstanceBeginEditable name="Code" -->
              <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # We can determine our object's class and its unique object ID
                # NIL is synonym for nil
                puts NIL.class # NilClass
                puts nil.class # NilClass
                puts nil.object_id # 4
                puts NIL.object_id # 4

                # FALSE is synonym for false
                puts FALSE.class # FalseClass
                puts false.class # FalseClass
                puts false.object_id # 0
                puts FALSE.object_id # 0
              </textarea>
              <!-- InstanceEndEditable -->
            </div>

            <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0">The Pragmatic Bookshelf</a>.</p>

            <p class="post-footer align-right">
              <strong>
                <a href="/satishtalim/more_on_strings.html">&lt;More on Strings | </a>
                <a href="/satishtalim/tutorial.html">TOC | </a>
                <a href="/satishtalim/ruby_blocks.html">Ruby Blocks&gt;</a>
              </strong>
            </p>

          </div>
          <!-- main inner ends here -->
        </div>

        <div id="rightbar">

        </div>

        <!-- content-wrap ends here -->
      </div>

      <!-- wrap ends here -->
    </div>

    <!-- footer starts here -->
    <div id="footer">
      <!-- CHANGE THE FOOTER -->
      <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
    </div>
    <!-- footer ends here -->

    <!-- SyntaxHighlighter code -->
    <script src="/js/shCore.js" type="text/javascript"></script>
    <script src="/js/shBrushRuby.js" type="text/javascript"></script>
    <script type="text/javascript">
     dp.SyntaxHighlighter.HighlightAll('code');
    </script>
    <!-- SyntaxHighlighter code -->
  </body>
</html>
